package com.cs5248;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

public class MainActivity extends ActionBarActivity {

	private static final int ACTION_TAKE_VIDEO = 0;
	private static final int ACTION_UPLOAD = 1;

	private static final String VIDEO_STORAGE_KEY = "viewvideo";
	private static final String VIDEOVIEW_VISIBILITY_STORAGE_KEY = "videoviewvisibility";
	private VideoView mVideoView;
	private TextView mTextView;
	private Uri mVideoUri;

	Button.OnClickListener mTakeVidOnClickListener = new Button.OnClickListener() {
		@Override
		public void onClick(View v) {
			dispatchTakeVideoIntent();
		}
	};

	Button.OnClickListener mUploadFileOnClickListener = new Button.OnClickListener() {
		@Override
		public void onClick(View v) {
			showFileChooser();
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mVideoView = (VideoView) findViewById(R.id.videoView1);
		mVideoUri = null;
		mTextView = (TextView) findViewById(R.id.textView);

		Button vidBtn = (Button) findViewById(R.id.btnIntendV);
		setBtnListenerOrDisable(vidBtn, mTakeVidOnClickListener, MediaStore.ACTION_VIDEO_CAPTURE);

		Button uploadBtn = (Button) findViewById(R.id.btnUpload);
		setBtnListenerOrDisable(uploadBtn, mUploadFileOnClickListener, Intent.ACTION_GET_CONTENT);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		switch (requestCode) {
		case ACTION_TAKE_VIDEO:
			if (resultCode == RESULT_OK) {
				mTextView.setText("Video successfully recorded!");
			} else {
				mTextView.setText("Video not recorded.");
			}
			break;
		case ACTION_UPLOAD:
			if (resultCode == RESULT_OK) {
				mTextView.setText("Video successfully uploaded!");
			} else {
				mTextView.setText("Video upload not successful...");
			}
			break;
		}
	}

	// Some lifecycle callbacks so that the image can survive orientation change
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putParcelable(VIDEO_STORAGE_KEY, mVideoUri);
		outState.putBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY, (mVideoUri != null));
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mVideoUri = savedInstanceState.getParcelable(VIDEO_STORAGE_KEY);
		mVideoView.setVideoURI(mVideoUri);
	}

	/**
	 * Indicates whether the specified action can be used as an intent. This method queries the package manager for
	 * installed packages that can respond to an intent with the specified action. If no suitable package is found, this
	 * method returns false. http://android-developers.blogspot.com/2009/01/can-i-use-this-intent.html
	 * 
	 * @param context
	 *            The application's environment.
	 * @param action
	 *            The Intent action to check for availability.
	 * 
	 * @return True if an Intent with the specified action can be sent and responded to, false otherwise.
	 */
	public static boolean isIntentAvailable(Context context, String action) {
		final PackageManager packageManager = context.getPackageManager();
		final Intent intent = new Intent(action);
		List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
		return list.size() > 0;
	}

	private void showFileChooser() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("*/*");
		intent.addCategory(Intent.CATEGORY_OPENABLE);

		try {
			startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), ACTION_UPLOAD);
		} catch (android.content.ActivityNotFoundException ex) {
			// Potentially direct the user to the Market with a Dialog
			Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
		}
	}

	private void setBtnListenerOrDisable(Button btn, Button.OnClickListener onClickListener, String intentName) {
		if (isIntentAvailable(this, intentName)) {
			btn.setOnClickListener(onClickListener);
		} else {
			btn.setText(getText(R.string.cannot).toString() + " " + btn.getText());
			btn.setClickable(false);
		}
	}

	private void dispatchTakeVideoIntent() {
		Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
		startActivityForResult(takeVideoIntent, ACTION_TAKE_VIDEO);
	}
}
